package outs

import "strings"

type Response struct {
	Code int    `json:"code"`
	Data any    `json:"data"`
	Msg  string `json:"msg"`
}

const (
	ERROR = iota
	SUCCESS
)

func Result(code int, data interface{}, msg string) Response {
	return Response{
		code,
		data,
		msg,
	}
}

func Ok() Response {
	return Result(SUCCESS, map[string]interface{}{}, "操作成功")
}

func OkWithMessage(message string) Response {
	return Result(SUCCESS, map[string]interface{}{}, message)
}

func OkWithData(data interface{}) Response {
	return Result(SUCCESS, data, "查询成功")
}

func OkWithDetailed(data interface{}, message string) Response {
	return Result(SUCCESS, data, message)
}

func Fail() Response {
	return Result(ERROR, map[string]interface{}{}, "操作失败")
}

func FailWithMessage(message string) Response {
	return Result(ERROR, map[string]interface{}{}, message)
}

func FailWithDetailed(data interface{}, message string) Response {
	return Result(ERROR, data, message)
}

// 类型方法接收者是值类型
func (t Response) GetData() any {
	if t.Code == SUCCESS {
		return t.Data
	} else {
		panic(t.Msg)
	}
}

func (t Response) GetDataLoginString() string {
	if t.Code == SUCCESS {
		json := t.Data.(string)
		if strings.Contains(json, "用户信息已过期，请重新登录") {
			panic("用户信息已过期，请重新登录")
		}
		return json
	} else {
		panic(t.Msg)
	}
}

type ResponseGeneric[T any] struct {
	Code int    `json:"code"`
	Data T      `json:"data"`
	Msg  string `json:"msg"`
}

func ResultGeneric[T any](code int, data T, msg string) ResponseGeneric[T] {
	return ResponseGeneric[T]{
		code,
		data,
		msg,
	}
}

func OkWithDataGeneric[T any](data T) ResponseGeneric[T] {
	return ResultGeneric(SUCCESS, data, "查询成功")
}

func FailWithDataGeneric[T any](data T, message string) ResponseGeneric[T] {
	return ResultGeneric(ERROR, data, message)
}

type Root[T any] struct {
	Data        Data[T] `json:"data"`
	DataPresent bool    `json:"dataPresent"`
}

type DataList[T any] struct {
	Node     T      `json:"node"`
	Typename string `json:"__typename"`
}
type PageInfo struct {
	TotalCount int    `json:"totalCount"`
	Typename   string `json:"__typename"`
}
type API[T any] struct {
	DataList []DataList[T] `json:"dataList"`
	PageInfo PageInfo      `json:"pageInfo"`
	Typename string        `json:"__typename"`
}
type Data[T any] struct {
	API API[T] `json:"api"`
}
